﻿using System;
using System.IO;
using SsrsRenderStudio.Shared;

namespace SsrsRenderStudio.Renderer.Output.Version2013
{
    public sealed class FileOutput : Output
    {
        protected new FileOutputParameters Parameters;

        public FileOutput(FileOutputParameters parameters) : base(parameters)
        {
            Parameters = parameters;
        }

        public override void Process()
        {
            writeToFile();
        }

        private void writeToFile()
        {
            try
            {
                //Logger.Log(EnumLoggingSeverity.DEBUGVERBOSE, "FileOutput: " + Parameters.DestinationFile.FullName);

                for (int i = 0; i < Parameters.RenderedReportBuffer.Length; i++)
                {
                    string file = Path.GetFileNameWithoutExtension(Parameters.DestinationFile.FullName);
                    string ext = Parameters.DestinationFile.Extension;
                    string filename = Parameters.DestinationFile.DirectoryName + @"\" + file + "." + i.ToString() + ext;

                    //Logger.Log(EnumLoggingSeverity.DEBUGVERBOSE, "FileOutput: Page: " + i.ToString() + "  Target: " + filename + " Bytes: " + this.Parameters.RenderedReportBuffer[i].Length);

                    try { File.Delete(filename); }
                    catch { }

                    // saving as true EMF: http://stackoverflow.com/questions/152729/gdi-c-how-to-save-an-image-as-emf/895204#895204
                    //_metafiles[i].Save(filename);

                    FileStream stream = File.Create(filename, this.Parameters.RenderedReportBuffer[i].Length);
                    stream.Write(this.Parameters.RenderedReportBuffer[i], 0, this.Parameters.RenderedReportBuffer[i].Length);
                    stream.Close();
                }
            }

            catch (Exception e)
            {
                Logger.Log("30001", e.Message);
            }
        }
    }
}
